﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using JPR.Common.Interfaces;

namespace JPR.Common.Implementations
{
    public class Logger : ILogger
    {
		#region Private methods

		private static void WriteLog(string message, LogCategory category, int priority, int eventId,
		                             TraceEventType severity, string title, IDictionary<string, object> properties)
		{
			Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(message, category.ToString(), priority, eventId,
			                                                           severity, title, properties);
		}

		#endregion

		#region Public methods

		#region Exception

		public void WriteException(Exception exception)
		{
			Dictionary<string, object> properties = new Dictionary<string, object> {{"Stack", exception.StackTrace}};
			Exception ex = exception;
			int i = 0;
			while (ex.InnerException != null)
			{
				properties.Add(string.Concat("Inner exception - Lvl ", i.ToString(CultureInfo.InvariantCulture)), ex.InnerException);
				foreach (DictionaryEntry entry in ex.Data)
				{
					properties.Add(string.Concat(" Lvl ", i.ToString(CultureInfo.InvariantCulture), " ", entry.Key.ToString()), entry.Value);
				}
				ex = ex.InnerException;
				i++;
			}
			WriteLog(exception.Message, LogCategory.Exception, 0, 0, TraceEventType.Critical, "Exception",
			         properties);
		}

		#endregion

		#region Trace

		public void WriteTrace(string message, string title, IDictionary<string, object> properties)
		{
			WriteLog(message, LogCategory.Trace, 0, 0, TraceEventType.Verbose, title, properties);
		}

		#endregion

		#endregion
	}

	public enum LogCategory
	{
		Exception,
		Error,
		Trace
	}
}